﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Mod.Events
{
    using SharingCenter.Web.Classes;
    using System.Collections;
    using SharingCenter.Web.Shared;
    using SharingCenter.Web.Classes.enums;
    using SharingCenter.Web.Classes.Requests;
    using SharingCenter.Web.Classes.Events;
    using System.Xml.Linq;
    using SharingCenter.Web.Classes.Groups;
    using SharingCenter.Web.Classes.Contact;
    using SharingCenter.Web.Classes.Favorites;
    using SharingCenter.Web.Classes.Accounts;
    

    public partial class ViewEvent : EventPageBase
    {
        protected static Sc_SharedRequest _request = null;

        protected Sc_Event _item;
        protected Guid eventId;
        protected bool isFavorite;
        //MultiView mvSignUp;
        protected bool isParticipant = false;
        scDataContext dcxt = new scDataContext();


        protected void Page_Init(object sender, EventArgs e)
        {
            FormView1.DataBound += new EventHandler(FormView1_DataBound);
            LinqDataSource1.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(LinqDataSource1_Selecting);
            SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(SiteMap_SiteMapResolve);
            lvSidebar.ItemDataBound += new EventHandler<ListViewItemEventArgs>(lvSidebar_ItemDataBound);
        }

        void lvSidebar_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            //ListViewDataItem item = (ListViewDataItem)e.Item;
            ListView lvParticipants = (ListView)e.Item.FindControl("lvParticipants");
            lvParticipants.DataSource = EventOperations.GetParticipantList(eventId, 999);
            lvParticipants.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] == null)
            {
                Response.Redirect("~/");
            }
            else
            {
                eventId = new Guid(Request.QueryString["id"]);
                isParticipant = Convert.ToBoolean(dcxt.IsUserEventParticipant(Profile.UserId, eventId));
            }

            _item = EventOperations.GetEventFromEvnetId(eventId);
            if (_item == null)
            {
                RedirectToDefaultPage();
            }

            try
            {
                using (scDataContext cxt = new scDataContext())
                {
                    _request = cxt.Sc_SharedRequests.SingleOrDefault(d => (d.RequestorUserId == Profile.UserId && d.ContextId == eventId));
                }
            }
            catch { }

            this.isFavorite = FavoriteOperations.GetFavorite("UserEvent", eventId, Profile.UserId) != null;
        }


        SiteMapNode SiteMap_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
        {
            SiteMapNode current = SiteMap.CurrentNode.Clone(true);
            SiteMapNode tmp = current;
            tmp.Title = _item.Title;
            return current;
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            SiteMap.SiteMapResolve -= new SiteMapResolveEventHandler(SiteMap_SiteMapResolve);
        }
        

        void lvComments_DataBinding(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }

        void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            List<Sc_Event> tmp = new List<Sc_Event>();
            tmp.Add(_item);
            e.Result = tmp;
            ltrTitle.Text = _item.Title;
            lvSidebar.DataSource = (List<Sc_Event>)e.Result;
            lvSidebar.DataBind();
        }


        void FormView1_DataBound(object sender, EventArgs e)
        {
            bool showContents = true;
            if (_item.Privacy == PrivacyEnum.Contacts)
            {
                showContents = RoleOperations.IsUserAdmin(Context.User.Identity.Name) || ContactOperations.AreUsersContacts(Profile.UserId, _item.CreatorUserId);
            }

            Panel pPanel = (Panel)FormView1.FindControl("pnPrivacyControl");
            Panel pCommentPanel = (Panel)FormView1.FindControl("pnCommentPrivacyControl");
            MessageBox pMsg = (MessageBox)FormView1.FindControl("msgPrivacy");

            if (!showContents)
            {
                pMsg.Visible = true;
                pPanel.Visible = false;
                pCommentPanel.Visible = false;
            }
            else
            {
                DisplayApprovedContents();
            }
        }

        protected void mvSignUp_PreRender(object sender, EventArgs e)
        {
            //if (_item == null) return;
            
        }

        void DisplayApprovedContents()
        {
            //MultiView mvVenue = (MultiView)FormView1.FindControl("mvVenue");

           // mvSignUp = (MultiView)FormView1.FindControl("mvSignUp");
            DisplayMessage();
            DisplayButtons();
        }

        private void DisplayButtons()
        {
            MultiView mv = (MultiView)FormView1.FindControl("mvSignUp");

            int view = 0;

            if (isParticipant)
            {
                view = 1;
            }
            else
            {
                if (DateTime.Now < _item.StartDate)
                {
                    if (_request != null)
                    {
                        // not started
                        switch (_request.Status)
                        {
                            case RequestStatus.Pending:
                                view = 1;
                                break;
                            case RequestStatus.Approved:
                                view = 1;
                                break;
                            default:
                                // mvVenue.ActiveViewIndex = 0;
                                view = 0;
                                break;
                        }
                    }
                    else
                    {
                        view = 0;
                    }
                }
            }

            mv.ActiveViewIndex = view;
        }

        void DisplayMessage()
        {
            MessageBox msg = (MessageBox)FormView1.FindControl("MessageBox1");
            string txt = string.Format("距活动开始只有{0}天了。", (_item.StartDate.Date - DateTime.Today).Days);
            if (_item.SignUpCloseDate < DateTime.Now)
            {
                txt = "报名已经结束，" + txt;
            }
            if (DateTime.Now > _item.EndDate)
            {
                txt = "此次活动已经结束。";
            }
            else
            {
                if (_request != null)
                {
                    if (_request.Status == SharingCenter.Web.Classes.enums.RequestStatus.Pending)
                    {
                        txt = "报名申请已经提交，正在等待审核。";

                    }
                    else if (_request != null && _request.Status == SharingCenter.Web.Classes.enums.RequestStatus.Approved)
                    {
                        txt = string.Format("报名已经被批准，距活动开始只有{0}天了。", (_item.StartDate.Date - DateTime.Today).Days);
                    }
                }
            }

            msg.Text = txt;
        }

        protected void SignUp(object sender, EventArgs e)
        {
            DoSignUp();
        }

        void DoSignUp()
        {
            if (_request == null || _request.Status != RequestStatus.Pending && _request.Status != RequestStatus.Approved)
            {
                AuthenticationRequired("");

                if (!_item.NeedApproval)
                {
                    EventOperations.AddParticipantToEvent(_item.EventId, Profile.UserId, "", true);
                    if (null != _request)
                    {
                        _request.Status = RequestStatus.Approved;
                    }
                }
                else
                {
                    XElement context = new XElement("Context",
                        new XAttribute("XsltFolderInMod", "Events"),
                            new XElement("EventId", eventId.ToString()),
                            new XElement("EventName", _item.Title));

                    //if (_item.EventSource == EntityType.GroupEvent)
                    //{
                    //    context.Add(new XElement("GroupId", _item.EventSourceId.ToString()),
                    //        new XElement("GroupName", GroupOperations.GetGroupByGroupId(_item.EventSourceId.Value).GroupName));
                    //}

                    _request = Classes.Requests.RequestOperations.AddRequest(_item.EventSource, eventId, Profile.UserId, _item.CreatorUserId, context);
                    //FormView1.DataBind();
                    
                }
                RefreshPage(true);
                /*
                try
                {
                    DisplayApprovedContents();
                }
                catch { RefreshPage(); }
                 */
                //dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, dataContext.Sc_SharedRequests);
                //SetTopMostMessage("报名成功。", true);
                //RefreshPage(true);
            }
            else
            {
                // Already signed up

            }
        }


        protected void DeleteComment(object sender, ContextHandlingEventArgs e)
        {
            Guid cid = (Guid)e.ContextValue;
        }

        protected void MessageBox1_PreRender(object sender, EventArgs e)
        {
            //DisplayMessage();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            DisplayMessage();
        }

        protected void ualFavoriteCollectors_Load(object sender, EventArgs e)
        {
            UserAvatarList ual = (UserAvatarList)sender;
            ual.UserIdList = FavoriteOperations.GetFavoriteCollectorUsers("UserEvent", eventId, 15);
        }
    }
}
